package com.googlecode.imule.data;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import com.googlecode.imule.redundant.CommThread;

/**
 * A class to server communication over UDP
 * @author Neil Cowzer, Mike Solomon
 */
public class UDPCommunicationX {

	// the packet to store the received information.
	private DatagramPacket infoPacket;
	
	// the outbound communication socket
	private DatagramSocket outSocket, inSocket;
	
	// the inbound communication listener
	private CommThread listener;
	
	/**
	 * Initialises a UDP communication stream
	 * @throws SocketException
	 */
	public UDPCommunicationX() throws SocketException {
		inSocket = new DatagramSocket();
		outSocket = new DatagramSocket();
		infoPacket = new DatagramPacket(new byte[4096], 4096);
		
		// DO I REALLY WANT TO DO THIS HERE?????
		/*listener = new CommThread(inSocket, infoPacket);
		listener.start();*/
	}
	
	
	/**
	 * 
	 * @return the infoPacket
	 */
	public DatagramPacket getInfoPacket() {
		return infoPacket;
	}


	/**
	 * 
	 * @return the inbound socket
	 */
	public DatagramSocket getInSocket() {
		return inSocket;
	}

	/**
	 * Takes string message and sends it through output socket
	 * @param message - string message
	 * @throws IOException
	 */
	public void send(String message, InetAddress address, int port) throws IOException{
		byte[] toSendData = message.getBytes("ISO-8859-1");
		DatagramPacket thePacket = new DatagramPacket(toSendData, toSendData.length);
		
		thePacket.setAddress(address);
		thePacket.setPort(port);
		outSocket.send(thePacket);
	}
	
	/*
	 * Used to close socket after application closes
	 */
	public void closeOutSocket(){
		this.outSocket.close();
	}
}
